<template>
  <div class="password-dialog">
    <div class="dialog-header">
      <h3>修改密码</h3>
      <button @click="$emit('close')" class="close-btn">×</button>
    </div>
    <div class="dialog-content">
      <!-- 第一步：手机验证 -->
      <div v-if="step === 1">
        <div class="form-group">
          <label>手机号验证</label>
          <input v-model="verifyPhone" type="tel" placeholder="确认手机号" readonly>
        </div>
        <div class="form-group">
          <label>验证码</label>
          <div class="verification-input">
            <input v-model="form.verifyCode" type="text" placeholder="请输入验证码" maxlength="4">
            <button @click="sendVerifyCode" :disabled="codeCountdown > 0" class="send-code-btn">
              {{ codeCountdown > 0 ? `${codeCountdown}s` : '发送验证码' }}
            </button>
          </div>
          <div v-if="generatedCode" class="generated-code">
            验证码: {{ generatedCode }}
          </div>
        </div>
      </div>

      <!-- 第二步：设置新密码 -->
      <div v-if="step === 2">
        <div class="form-group">
          <label>新密码</label>
          <input v-model="form.newPassword" type="password" placeholder="请输入新密码">
          <small>密码长度至少6位</small>
        </div>
        <div class="form-group">
          <label>确认新密码</label>
          <input v-model="form.confirmPassword" type="password" placeholder="请再次输入新密码">
        </div>
      </div>
    </div>
    <div class="dialog-actions">
      <button @click="$emit('close')" class="cancel-btn">取消</button>
      <button v-if="step === 2" @click="step = 1" class="cancel-btn">上一步</button>
      <button v-if="step === 1" @click="nextToPasswordChange" class="confirm-btn">下一步</button>
      <button v-if="step === 2" @click="savePassword" class="confirm-btn">确认修改</button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'PasswordChangeModal',
  props: {
    userPhone: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      step: 1,
      form: {
        verifyCode: '',
        newPassword: '',
        confirmPassword: ''
      },
      verifyPhone: this.userPhone,
      codeCountdown: 0,
      generatedCode: ''
    }
  },
  methods: {
    async sendVerifyCode() {
      if (this.codeCountdown > 0) return;

      try {
        const response = await this.$root.$http.post('/api/users/send-code', null, {
          params: { phone: this.verifyPhone }
        });

        if (response.success) {
          if (response.verificationCode) {
            this.generatedCode = response.verificationCode;
          }

          this.codeCountdown = 60;
          const timer = setInterval(() => {
            this.codeCountdown--;
            if (this.codeCountdown <= 0) {
              clearInterval(timer);
            }
          }, 1000);

          this.$root.showToast('验证码已发送', 'success');
        } else {
          this.$root.showToast(response.message || '发送验证码失败', 'error');
        }
      } catch (error) {
        console.error('发送验证码失败:', error);
        const errorMessage = error.response?.data?.message || '发送验证码失败，请重试';
        this.$root.showToast(errorMessage, 'error');
      }
    },

    nextToPasswordChange() {
      if (!this.form.verifyCode || this.form.verifyCode.length !== 4) {
        this.$root.showToast('请输入4位验证码', 'warning');
        return;
      }
      this.step = 2;
    },

    async savePassword() {
      if (!this.form.newPassword) {
        this.$root.showToast('请输入新密码', 'warning');
        return;
      }
      if (this.form.newPassword.length < 6) {
        this.$root.showToast('新密码至少需要6位', 'warning');
        return;
      }
      if (!this.form.confirmPassword) {
        this.$root.showToast('请输入确认密码', 'warning');
        return;
      }
      if (this.form.newPassword !== this.form.confirmPassword) {
        this.$root.showToast('两次输入的密码不一致', 'warning');
        return;
      }

      try {
        const passwordData = {
          verificationCode: this.form.verifyCode,
          newPassword: this.form.newPassword,
          confirmPassword: this.form.confirmPassword
        };

        const userToken = localStorage.getItem('userToken');
        const userExpiry = localStorage.getItem('userTokenExpiry');
        if (!userToken || !userExpiry || Date.now() > parseInt(userExpiry)) {
          this.$root.showToast('登录已过期，请重新登录', 'error');
          this.$router.push('/users/login');
          return;
        }

        const response = await this.$root.$http.post('/api/users/change-password', passwordData, {
          headers: {
            'Authorization': `Bearer ${userToken}`
          }
        });

        if (response.success) {
          this.$root.showToast('密码修改成功', 'success');
          this.$emit('close');
        } else {
          this.$root.showToast(response.message || '修改失败', 'error');
        }
      } catch (error) {
        console.error('修改密码失败:', error);
        const errorMessage = error.response?.data?.message || '修改失败，请重试';
        this.$root.showToast(errorMessage, 'error');
      }
    }
  }
}
</script>

<style scoped>
.password-dialog {
  background: #181818;
  border-radius: 8px;
  width: 500px;
  overflow: hidden;
  animation: slideIn 0.3s ease;
  border: 1px solid #333;
}

.dialog-header {
  padding: 20px 24px;
  border-bottom: 1px solid #333;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-header h3 {
  margin: 0;
  color: white;
  font-size: 18px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  color: #b3b3b3;
  font-size: 24px;
  cursor: pointer;
  padding: 0;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.close-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  color: white;
}

.dialog-content {
  padding: 24px;
  color: #b3b3b3;
  line-height: 1.5;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  color: white;
  font-size: 14px;
  font-weight: 600;
  margin-bottom: 8px;
}

.form-group input {
  width: 100%;
  height: 44px;
  background: #121212;
  border: 1px solid #727272;
  border-radius: 4px;
  color: white;
  font-size: 14px;
  padding: 0 12px;
  transition: border-color 0.3s ease;
}

.form-group input:focus {
  outline: none;
  border-color: white;
}

.form-group input[readonly] {
  background: #282828;
  color: #b3b3b3;
}

.form-group small {
  display: block;
  color: #b3b3b3;
  font-size: 12px;
  margin-top: 4px;
}

.verification-input {
  display: flex;
  gap: 12px;
  align-items: center;
}

.verification-input input {
  flex: 1;
}

.send-code-btn {
  background: #1db954;
  border: none;
  color: black;
  padding: 0 16px;
  height: 44px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.send-code-btn:hover:not(:disabled) {
  background: #1ed760;
}

.send-code-btn:disabled {
  background: #535353;
  cursor: not-allowed;
}

.generated-code {
  font-size: 12px;
  color: #1db954;
  font-weight: bold;
  margin-top: 8px;
  padding: 8px 12px;
  background: rgba(29, 185, 84, 0.1);
  border: 1px solid rgba(29, 185, 84, 0.3);
  border-radius: 6px;
  text-align: center;
}

.dialog-actions {
  padding: 16px 24px 24px;
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.cancel-btn,
.confirm-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
  min-width: 80px;
}

.cancel-btn {
  background: transparent;
  color: #b3b3b3;
  border: 1px solid #535353;
}

.cancel-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  color: white;
  border-color: #727272;
}

.confirm-btn {
  background: #1db954;
  color: black;
}

.confirm-btn:hover:not(:disabled) {
  background: #1ed760;
  transform: scale(1.02);
}

.confirm-btn:disabled {
  background: #535353;
  cursor: not-allowed;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style> 